#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;
pthread_spinlock_t spin;
volatile size_t ticket = 10000;
//自旋锁的使用场景为临界区很短,等待锁的时间一般较短
//没有必要阻塞等待,直接一直轮询代替阻塞,提高效率.
//当若使用不当,会浪费大量cpu资源
//操作与互斥锁基本一致
void *thread_routine(void *argc)
{
    while (1)
    {
        cout << (size_t)argc << ": ";
        pthread_spin_lock(&spin);
        if (ticket)
        {
            cout << ticket-- << endl;
            pthread_spin_unlock(&spin);
            usleep(999);
        }
        else
        {
            pthread_spin_unlock(&spin);
            cout << "none..." << endl;
            usleep(123);
            break;
        }
    }
}
int main()
{
    //自旋锁 不是真正的挂起等待,而是自动不停的轮询检测
    //不支持宏初始化
    pthread_spin_init(&spin, PTHREAD_PROCESS_PRIVATE); // 0
    size_t thread_num = 3;
    pthread_t thread[thread_num];
    for (int i = 0; i < thread_num; i++)
        pthread_create(thread + i, nullptr, thread_routine, (void *)i);
    for (int i = 0; i < thread_num; i++)
        pthread_join(thread[i], nullptr);
    pthread_spin_destroy(&spin);
    return 0;
}